package com.ou.csbs.capstone.controllers.menu;

import gov.nasa.worldwind.geom.Position;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import com.ou.csbs.capstone.gridlines.ExtendedUTMLayer;
import com.ou.csbs.capstone.gridlines.UTMCoord;
import com.ou.csbs.capstone.views.menu.MenuBar;
import com.ou.csbs.capstone.views.worldwind.WorldWindCanvas;
/**
 * Controller class for menu bar items. This includes enabling and disabling all of the Grid Line systems.
 * 
 * @author Senior Capstone
 */
public class MenuBarController {
	private MenuBar menuBar;

	public MenuBarController() {

	}

	public void setMenuBar(MenuBar menubar){
		this.menuBar = menubar;
		addActionListener();
	}

	private class buttonListener implements ActionListener {
		public void actionPerformed(ActionEvent e){
			if(e.getSource() == menuBar.getQuit()){
				System.exit(0);
			}
			else if(e.getSource() == menuBar.getLatLong()){
				turnLayersOff();
				WorldWindCanvas.turnLayerOn("LatLongLayer");
			}
			else if(e.getSource() == menuBar.getUTM()){
				turnLayersOff();
				WorldWindCanvas.turnLayerOn("UTMLayer");

			}
			else if(e.getSource() == menuBar.getEUTM()){
				Position position = WorldWindCanvas.getWorldWindow().getView().getCurrentEyePosition();
				//cleanup position for UTM conversion
				if(position.getLatitude().getDegrees() > 84)
					position = Position.fromDegrees(84, position.getLongitude().getDegrees());
				if(position.getLatitude().getDegrees() < -80)
					position = Position.fromDegrees(-80, position.getLongitude().getDegrees());
				ExtendedUTMLayer eutm = new ExtendedUTMLayer();
				eutm.setCoordInZone(UTMCoord.fromLatLon(position.getLatitude(), position.getLongitude()));
				turnLayersOff();
				WorldWindCanvas.addLayer(eutm);
			}
			else if(e.getSource() == menuBar.getOff()){
				turnLayersOff();
			}
		}
	}

	public void addActionListener(){
		menuBar.getQuit().addActionListener(new buttonListener());
		menuBar.getLatLong().addActionListener(new buttonListener());
		menuBar.getUTM().addActionListener(new buttonListener());
		menuBar.getEUTM().addActionListener(new buttonListener());
		menuBar.getOff().addActionListener(new buttonListener());
	}
	
	private void turnLayersOff(){
		WorldWindCanvas.turnLayerOff("LatLongLayer");
		WorldWindCanvas.turnLayerOff("UTMLayer");
		WorldWindCanvas.removeLayer("ExtendedUTMLayer");
	}
}
